import shapefile

r = shapefile.Reader("shapefiles/roads/roadtrl020")
w = shapefile.Writer("shapefiles/roads/Puerto_Rico_Roads")
# 复制字段
w.fields = list(r.fields)
xmin = -67.5
xmax = -65.0
ymin = 17.8
ymax = 18.6
for road in r.iterShapeRecords():
    geom = road.shape
    rec = road.record
    # 圈定范围，如果在范围外，跳出本次循环
    sxmin, symin, sxmax, symax = geom.bbox
    if sxmin < xmin:
        continue
    elif sxmax > xmax:
        continue
    elif symin < ymin:
        continue
    elif symax > ymax:
        continue
    # 复制记录和图形
    w.record(*rec)
    w.poly([geom.points])
r.close()
w.close()

# 查看成果
r = shapefile.Reader("shapefiles/roads/Puerto_Rico_Roads")
print(r)
r.close()
